package com.rjwh.dingdong.client.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.aishua.lib.utils.AsLog;
import com.aishua.lib.utils.AsStrUtils;
import com.baidu.mobstat.StatService;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.ThemeUtils;
import com.rjwh.dingdong.client.widget.MyProgressDialog;
import com.rjwh.dingdong.client.application.AppManager;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public abstract class BaseActivity extends AppCompatActivity {


    private MyProgressDialog mProgressDialog;
    private int theme = 0;// 当前界面设置的主题
    public CompositeSubscription mCompositeSubscription;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        if (savedInstanceState == null) {
//            theme = configTheme();
//        } else {
//            theme = savedInstanceState.getInt("theme");
//        }
//        // 设置主题
//        if (theme > 0)
//            setTheme(theme);

        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        LogUtil.e("BaseActivity", "AppManager.activityStack.size():" + AppManager.getAppManager().getActivitySize());
        this.mCompositeSubscription = new CompositeSubscription();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        StatService.onPause(this);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        StatService.onResume(this);
//        if (theme != configTheme()) {
//            reload();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        onUnsubscribe();
        AppManager.getAppManager().finishActivity(this);
        LogUtil.e("BaseActivity", "AppManager.onDestroy" + AppManager.getAppManager().getActivitySize());
    }

//    @Override
//    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        outState.putInt("theme", theme);
//        LogUtil.d("onSaveInstanceState");
//    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        LogUtil.e("SplashActivity", "onRestoreInstanceState");
        MyApplication.getInstance().restApp();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        LogUtil.d("MorePersonDataActivity onSaveInstanceState");
    }


    protected int configTheme() {
        int spTheme = MyApplication.spUtil.getIntPreferenceByParamName(this, "theme");
        if (spTheme == -1) spTheme = 0;
        int theme = ThemeUtils.themeArr[spTheme][0];
        if (theme > 0)
            return theme;
        return -1;
    }

    public void reload() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        // intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }


    public void showLoadDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            return;
        }
        String title = getResources().getString(R.string.dialog_title_waitting);
        try {
            if (mProgressDialog == null) {
                mProgressDialog = new MyProgressDialog(this, title);
                mProgressDialog.show();
            } else if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }
        } catch (Exception e) {
            AsLog.e("BaseActivity", "progressDialog error", e);
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v, ev)) {
                hideInput();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     *
     * @param v
     * @param event
     * @return
     */
    protected boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int top = l[1], bottom = top + v.getHeight();
            if (event.getY() > top && event.getY() < bottom) {
                // 点击EditText的事件，忽略它。
                return false;
            } else {
                v.getLocationOnScreen(l);
                int Y = l[1] + v.getHeight();
                if (event.getRawY() < Y) {// 只有点击EditText上方空白才隐藏
                    return true;
                }
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    public void dismissLoadDialog() {
        if (!isFinishing() && mProgressDialog != null
                && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        mProgressDialog = null;
    }

    public void showInputMethodWindow(final EditText editContent) {

        InputMethodManager im = (InputMethodManager) editContent
                .getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        im.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }

    public void hideInputMethodWindow(final EditText editContent) {

        InputMethodManager im = (InputMethodManager) editContent
                .getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(editContent.getWindowToken(), 0);

    }

    protected void hideInput() {

        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null && getCurrentFocus() != null) {
            im.hideSoftInputFromWindow(getCurrentFocus()
                            .getApplicationWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }

    public void hideSoftInputView() {

        // TODO Auto-generated method stub
        InputMethodManager manager = ((InputMethodManager) BaseActivity.this
                .getSystemService(Activity.INPUT_METHOD_SERVICE));
        if (getWindow().getAttributes().softInputMode != LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.hideSoftInputFromWindow(getCurrentFocus()
                                .getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }

    }

    public void showToast(String toast) {
        if (AsStrUtils.isEmpty(toast)) {
            return;
        }
        Toast.makeText(BaseActivity.this, toast, Toast.LENGTH_SHORT).show();
    }

    public static void showToast(Context context, String toast) {
        if (AsStrUtils.isEmpty(toast)) {
            return;
        }
        Toast.makeText(context, toast, Toast.LENGTH_SHORT).show();
    }

    //RXjava取消注册，以避免内存泄露
    public void onUnsubscribe() {
        if (mCompositeSubscription != null && mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }


    public void addSubscription(Observable observable, Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(observable
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber));
    }

    public void addSubscription(Subscriber subscriber) {
        if (mCompositeSubscription == null) {
            mCompositeSubscription = new CompositeSubscription();
        }
        mCompositeSubscription.add(subscriber);
    }
}
